import React, { useEffect, useMemo, useState } from 'react'
import { Divider, Dropdown, Empty } from 'antd';
import './style.less'
import DataPreprocessField from './DataPreprocessField';
import { Header } from './Header';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useNodesData, useReactFlow } from '@xyflow/react';
import { RESULT_SHOW_MODE_DICT } from '@/constant/icons';
import { usePreviousNodes } from '@/hooks/usePreviousNodes';
import { cloneDeep, isEqual } from 'lodash-es';
import { AnimatePresence, motion } from 'motion/react';
import S2Table from '../../common/S2Table';


export const DataPreprocess = () => {
  const currentNode = useCurrentNode()
  const nodeData = useNodesData(currentNode?.id)
  const preNode = usePreviousNodes(currentNode?.id)?.[0]
  const preNodeData = useNodesData(preNode?.id)
  const { updateNodeData } = useReactFlow()

  const columns = nodeData?.data?.columns ?? []
  const allColumns = nodeData?.data?.allColumns ?? []
  const select = columns?.length ?? 0

  const [searchValue, setSearchValue] = useState('')
  const [showMode, setShowMode] = useState(RESULT_SHOW_MODE_DICT.field)

  const fetchColumns = () => {
    const preColumns = preNodeData?.data?.columns
    if (isEqual(preColumns, allColumns)) return
    updateNodeData(currentNode?.id, { allColumns: cloneDeep(preColumns) })
  }

  useEffect(() => {
    if (preNodeData) {
      fetchColumns()
    }
  }, [preNodeData])

  const searchResult = useMemo(() => {
    if (!searchValue) return allColumns
    return allColumns?.filter(s => s.columnName?.indexOf(searchValue) > -1)
  }, [allColumns, searchValue])

  const handleSelectionChange = (items) => {
    const selection = new Set(items)
    const columns = allColumns?.filter((d) => {
      return selection.has(d.columnId)
    })
    updateNodeData(currentNode?.id, { columns })
  }

  const handleChange = (row) => {
    const fieldMapper = (field) => {
      return field.columnId === row.columnId ? { ...row } : field
    }
    const updatedAllColumns = allColumns?.map(fieldMapper)
    const updatedColumns = columns?.map(fieldMapper)
    updateNodeData(currentNode?.id, { allColumns: updatedAllColumns, columns: updatedColumns })
  }
  const selectedRowKeys = useMemo(() => {
    return columns?.map(c => c?.columnId) || []
  }, [columns])

    const renderContent = () => {
      if (!preNode) {
        return (
          <motion.div
            key="empty"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.2 }}
          >
            <Empty description="请先连接上游节点" />
          </motion.div>
        );
      }
  
      switch (showMode) {
        case RESULT_SHOW_MODE_DICT.data:
          return (
            <motion.div
              key="data"
              initial={{ opacity: 0, x: 10 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -10 }}
              transition={{ duration: 0.2 }}
            >
              <S2Table columns={[]} dataSource={[]} />
            </motion.div>
          );
        default:
          return (
            <motion.div
              key="default-empty"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.2 }}
            >
              <Empty />
            </motion.div>
          );
      }
    };

  return (
    <div className='preprocess-container'>
      <Header total={allColumns?.length ?? 0}
        select={select}
        mode={showMode}
        onChange={setShowMode}
        onSearch={setSearchValue} />
      <Divider style={{ margin: '10px 0' }} />
      <AnimatePresence mode="wait">
          {renderContent()}
        </AnimatePresence>
      {/* <div className='preprocess-body'>
        <DataPreprocessField dataSource={searchResult}
          onSelectionChange={handleSelectionChange}
          onChange={handleChange} selectedRowKeys={selectedRowKeys} />
      </div> */}
    </div>
  );
};